package com.google.code.mochaccino.framework.ui.demo.pages;

import com.mycila.inject.internal.guava.io.NullOutputStream;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.BodyPartEntity;
import com.sun.jersey.multipart.MultiPart;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;

@Path( "/upload" )
public class SomeFileUpload {

	@GET
	@Produces( MediaType.TEXT_HTML )
	public void doGet( @Context HttpServletResponse rp ) throws IOException {
		PrintWriter out = rp.getWriter();
		out.write( "<html><body><form id='frm' action='' method='post' enctype='multipart/form-data'><input id='file' name='file' type='file'></input><input id='submit' type='submit' /></form></body></html>" );
		out.flush();
	}

	@POST
	@Consumes( MediaType.MULTIPART_FORM_DATA )
	@Produces( MediaType.TEXT_PLAIN )
	public void doUpload( @Context HttpServletRequest rq, @Context HttpServletResponse rp, MultiPart p ) throws IOException {
		for ( BodyPart part : p.getBodyParts() ) {
			BodyPartEntity e = (BodyPartEntity) part.getEntity();
			IOUtils.copy( e.getInputStream(), new NullOutputStream() );
		}
	}
}
